package com.scau.os.MemorySys;

import com.scau.os.course_manager.bean.PCB;
import com.scau.os.extension.EventSystem;

/**
 * 该类用来使用内存
 */



/**
 * 内存管理器
 */
public class UseMemory {
    public static final Memory memory =new Memory(512);
    public boolean FF(Memory memory, int size,PCB pcb) {
        /**
         * FF方法是用来申请内存，传入内存memory,需要申请的大小size，对应进程的PCB
         * 如果申请成功，就会返回True，否则返回FALSE
         * @param memory
         * @param size
         * @param pcb
         * @return
         */
        int sum = 0;
        for (int i = 0; i < memory.getHoles().size(); i++) {    //循环内存中所有分区
            sum++;
            Hole hole = memory.getHoles().get(i);   //获得对应的分区
            if (hole.isFree() && hole.getSize() >= size) {  //若此分区空闲且大小大于申请的大小，则申请内存
                System.out.println("查找" + sum + "次");
                memory = memory.getMemory(size, i, hole,pcb);
                EventSystem.instance.SendEvent("RefreshMemory",null);
                return true;
            }
        }
        System.err.println("OUT OF MEMORY!");
        return false;
    }

    /**
     * 该方法用来释放内存，传入进程id
     * 成功释放返回TRUE，否则返回FALSE
     * @param memory
     * @return
     */
    public boolean release(Memory memory,PCB pcb){
        int id = Integer.parseInt(pcb.getProcessID());
        boolean isok = memory.releaseMemory(id);
        return isok;
    }
    public UseMemory(){

    }
    public void showMemory(Memory memory) {
        System.out.println("------------------------------------");
        System.out.println("分区编号\t分区始址\t分区大小\t空闲状态\t");
        System.out.println("------------------------------------");
        for (int i = 0; i < memory.getHoles().size(); i++){
            Hole hole = memory.getHoles().get(i);
            System.out.println(i + "\t\t" + hole.getHead() + "\t\t" + hole.getSize() + "  \t" + hole.isFree());
        }
        System.out.println("------------------------------------");
    }

    public void showPcbs(Memory memory) {
        System.out.println("------------------------------------");
        System.out.println("进程编号\t进程状态\t进程起始地址\t进程大小\t");
        System.out.println("------------------------------------");
        if (memory.getPcbs().size() > 0) {
            for (int i = 0; i < memory.getPcbs().size(); i++) {
                PCB pcb = memory.getPcbs().get(i);
//                System.out.println(pcb.getId() + "  \t" + pcb.getState() + "\t\t" + pcb.getHole().getHead() + "\t\t\t" + pcb.getHole().getSize());
            }
        } else {
            System.err.println("\t\t\t暂无进程！");
        }
        System.out.println("------------------------------------");
    }
    public void show(Memory memory){
        showPcbs(memory);
        showMemory(memory);
    }

}
